package com.ltxtiyu.video.api;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ltxtiyu.video.common.ConfigConstant;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.service.app.OauthService;
import com.ltxtiyu.video.tool.ParamTool;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 关于登陆认证
 */
@RestController
public class ApiOauth {
    @Autowired
    DefaultKaptcha captchaProducer;

    @Reference
    OauthService oauthService;

    /**
     * 发送验证码
     * @param request
     * @return
     */
    @RequestMapping("/apiOauth/captcha")
    public String captcha(HttpServletRequest request){
        Map<String, String> stringObjectMap = ParamTool.requestToParamMap(request);
        return oauthService.captcha(stringObjectMap);
    }

    /**
     * 手机号注册
     * @param request
     * @return
     */
    @RequestMapping("/apiOauth/register")
    public String register(HttpServletRequest request){
        Map<String, String> stringObjectMap = ParamTool.requestToParamMap(request);
        String resultRegister = oauthService.register(stringObjectMap);
        JSONObject jsonObject = JSON.parseObject(resultRegister);
        Integer userId = jsonObject.getInteger("userId");
        /**
         * 注册成功后session中存入userId, 并返回userId
         */
        if(userId != null && userId >= 0){
            // 给userId进行hashid加密
            Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);
            String hashUserId = hashids.encode(userId);
            request.getSession().setAttribute("userId",hashUserId);
            jsonObject.put("userId",hashUserId);
        }
        return jsonObject.toJSONString();
    }


    /**
     * 图形验证码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/kaptcha.jpg")
    public ModelAndView kaptcha(HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();  // 图形验证码 存入session
        request.getSession().setAttribute("KAPTCHA_CODE",capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 潘那段图像验证码是否正确
     * @param request
     * @return
     */
    @RequestMapping("/checkCaptcha")
    @ResponseBody
    public String checkCaptcha(HttpServletRequest request){
        // 校验图形验证码
        String kaptcha_code = (String) request.getSession().getAttribute("KAPTCHA_CODE");
        String picCaptcha = request.getParameter("picCaptcha");
        if(picCaptcha == null || !picCaptcha.equals(kaptcha_code)){ // 图形验证码错误
            return JsonTool.genJson(RetEnum.OAUTH_PIC_CAPTCHA_CHECK_ERROR);
        }
        return JsonTool.genJson(RetEnum.SUCCESS);
    }
}
